<?php
/**
 * [ Random Framework ]
 *
 * @version 2.0.0 (build 20130520)
 *
 * @link http://0x00.sinaapp.com/random.html
 * 
 * @author Coseylee (Coseylee@gmail.com).
 *
 */

/**
 * 生成 RUNTIME 执行文件
 * 
 */
function random_runtime()
{
	$runtime = RANDOM_ROOT.'~runtime.php';
	
	$files = array(
		'random.db.php',
		'random.cache.php',
		'random.exception.php',
		'random.interface.datebase.php',
		'random.interface.model.php',
		'random.interface.service.php',
		'random.interface.controller.php',
		'random.interface.route.php',
	);
	
	if ($GLOBALS['RANDOM']['onruntime'] == true)
	{
		if (!file_exists($runtime))
		{
			$code = '';
			foreach ($files as $file)
			{
				$code .= php_strip_whitespace(RANDOM_ROOT.$file);
			}
			file_put_contents($runtime, '<?php /* Latest Update At '.date('Y-m-d H:i:s').' */ '.str_replace(array('<?php', "\n"), '', $code));
		}
		include $runtime;
	}
	else
	{
		foreach ($files as $file)
		{
			include RANDOM_ROOT.$file;
		}
	}

	foreach (array('controller', 'service', 'route') as $name)
	{
		if ($GLOBALS['RANDOM']['my_'.$name.'_file'])
		{
			random::import($GLOBALS['RANDOM']['my_'.$name.'_file']);
		}
	}

	return true;
}

/**
 * 合并配置文件
 * 
 * @param $default 默认配置
 * @param $user 用户配置
 */
function merge_config($default, $user)
{
	$config = $default;
	foreach ($user as $key => $value)
	{
		if (!is_array($value))
		{
			$config[$key] = $value;
		}
		else
		{
			$config[$key] = isset($config[$key]) && is_array($config[$key]) ? merge_config($config[$key], $value) : $value;
		}
	}
	return $config;
}

/**
 * 加载并解析模版文件
 * 
 * @param $file 模版文件名
 * @param $controller 模版目录
 * @param $ext 模版文件后缀
 */
function template($file, $controller = '', $ext = '.tpl.php')
{
	$config = $GLOBALS['RANDOM']['template'];
	
	$controller = $controller == '' ? CONTROLLER : $controller;
	
	$source_file = $config['template_dir'].$controller.$config['separator'].$file.$ext;
	$cache_file = $config['cache_dir'].$controller.$config['separator'].$file.$ext;
	
	// 源文件不存在
	if (!file_exists($source_file))
	{
		throw new random_exception('Template File ('.$controller.$config['separator'].$file.') Not Found.');
	}
	
	// 没有缓存或已被修改过
	if (!file_exists($cache_file) || filemtime($cache_file) < filemtime($source_file))
	{
		if (!is_dir($config['cache_dir']))
		{
			mkdir($config['cache_dir']);
		}
		
		if (($config['separator'] == '/' || $config['separator'] == '\\') && !is_dir($config['cache_dir'].$controller))
		{
			mkdir($config['cache_dir'].$controller);
		}
		
		$content = file_get_contents($source_file);
		$content = preg_replace('/\{include\s+(.+)\}/iU', "<?php include '\\1'; ?>", $content);
		$content = preg_replace('/\{template\s{0,}\((.+)\)\}/iU', '<?php include template(\\1); ?>', $content);
		$content = preg_replace('/\{if\s+(.+)\}/iU', '<?php if (\\1): ?>', $content);
		$content = preg_replace('/\{else\}/iU', '<?php else: ?>', $content);
		$content = preg_replace('/\{elseif\s+(.+)\}/iU', '<?php elseif (\\1): ?>', $content);
		$content = preg_replace('/\{\/if\}/iU', '<?php endif; ?>', $content);
		$content = preg_replace('/\{loop\s+(\S+)\s+(\S+)\}/iU', '<?php if (is_array(\\1)) $i = 0 ; foreach (\\1 as \\2): $i++; ?>', $content);
		$content = preg_replace('/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/iU', '<?php if (is_array(\\1)) $i = 0 ; foreach (\\1 as \\2 => \\3): $i++; ?>', $content);
		$content = preg_replace('/\{\/loop\}/iU', '<?php endforeach; ?>', $content);
		$content = preg_replace('/\{for\s+(.+?)\}/iU',"<?php for(\\1): ?>", $content);
		$content = preg_replace('/\{\/for\}/iU',"<?php endfor; ?>", $content);
		$content = preg_replace('/\{php\}/iU', '<?php ', $content);
		$content = preg_replace('/\{\/php\}/iU', '; ?>', $content);
		$content = preg_replace('/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/iU', '<?php echo \\1; ?>', $content); // 普通函数
		$content = preg_replace('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/iU', '<?php echo \\1; ?>', $content); // 变量函数
		$content = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\[[\"\']?.*[\"\']?\])*)\}/iU', '<?php echo \\1; ?>', $content); // 普通变量
		$content = preg_replace('/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/iUs', '<?php echo \\1; ?>', $content); // 普通常量
		$content = '<?php /* Last Updated At '.date('Y-m-d H:i:s').'*/ ?>'.PHP_EOL.$content;
		
		if (@!file_put_contents($cache_file, $content))
		{
			throw new random_exception('Write To Template Cache File Failed.');
		}
		unset($content);
		return $cache_file;
	}
	
	return $cache_file;
}

/**
 * 生成访问URL链接
 * 
 * @param $controller 控制器
 * @param $action 动作
 * @param $args 其它参数（数组）
 */
function url($controller = '', $action = '', $args = array(), $query_string = '')
{
	return $GLOBALS['RANDOM']['route']['router'] -> url_create($controller, $action, $args, $query_string);
}

/**
 * 分页函数
 * 
 * @param $Total 总数
 * @param $Pages 总页数
 * @param $curPage 当前页
 * @param $argName 分页标识名
 */
function showPageLinks($Total, $Pages, $curPage, $argName = 'page')
{
	$get = $_GET;
	if (isset($get[$GLOBALS['RANDOM']['route']['controller_name']])) unset($get[$GLOBALS['RANDOM']['route']['controller_name']]);
	if (isset($get[$GLOBALS['RANDOM']['route']['action_name']])) unset($get[$GLOBALS['RANDOM']['route']['action_name']]);
	
	$links = '<div class="pages">';
	$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => 1))).'">第一页</a>';
	if ($Pages <= 20)
	{
		for ($i = 1;$i <= $Pages && $i <= 20;$i++)
		{
			$class = $curPage == $i ? 'class="cur"' : '';
			$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $i))).'" '.$class.'>'.$i.'</a>';
			if ($i == 20)
			{
				$links .= '....<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $Pages))).'">'.$Pages.'</a>';
			}
		}
	}
	else
	{
		for ($i = 1,$j = 0;$i <= 5;$i++)
		{
			$j = $curPage - (6 - $i);
			if ($j >= $curPage || $j <= 0) continue;
			$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $j))).'">'.$j.'</a>';
		}
		$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $curPage))).'" class="cur">'.$curPage.'</a>';
		for ($i = 1,$j = 0;$i <= 5;$i++)
		{
			$j = $curPage + $i;
			if ($j > $Pages) continue;
			$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $j))).'">'.$j.'</a>';
		}
	}
	$links .= '<a href="'.url(CONTROLLER, ACTION, array_merge($get, array($argName => $Pages))).'">最后一页</a>';
	$links .= ' 共 '.$Pages.' 页,共计 '.$Total.' 条记录</div>';
	return $links;
}

/**
 * 当前页面URL
 * 
 * @param $return_query 不返回域名部分
 */
function thisURL($return_query = false)
{
	$url = isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on' ? 'https://' : 'http://';
	$url .= $_SERVER['HTTP_HOST'].($_SERVER["SERVER_PORT"] == '80' ? '' : ':'.$_SERVER["SERVER_PORT"]);
	//$_SERVER["REQUEST_URI"] 只有 apache 才支持
	if (isset($_SERVER['REQUEST_URI']))
	{
		$query = $_SERVER['REQUEST_URI'];
	}
	else
	{
		if (isset($_SERVER['QUERY_STRING']))
		{
			$query = $GLOBALS['RANDOM']['route']['url_base'].'?'.$_SERVER['QUERY_STRING'];
		}
		else if(isset($_SERVER['argv']))
		{
			$query = $GLOBALS['RANDOM']['route']['url_base'].'?'.$_SERVER['argv'][0];
		}
	}
	return $return_query == false ? $url.$query : $query;
}

/**
 * 跨站提交
 * 
 */
function formcheck()
{
	if ($_SERVER['REQUEST_METHOD'] != 'POST') return true;
	if (!empty($_SERVER['HTTP_REFERER']) && preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST']))
	{
		return true;
	}
	return false;
}

/**
 * 打印出变量信息
 * 
 * @param $vars 需要打印的变量
 */
function dump($vars)
{
	echo "<div align=left><pre>\n".htmlspecialchars(print_r($vars, true))."\n</pre></div>\n";
}

/**
 * 添加转义
 * 
 * @param $str 准备处理的字符
 */
function add_slashes($str)
{
	$str = is_array($str) ? array_map('add_slashes', $str) : addslashes($str);
	return $str;
}

/**
 * 添加转义
 * 
 * @param $str 准备处理的字符
 */
function strip_slashes($str)
{
	$str = is_array($str) ? array_map('strip_slashes', $str) : stripslashes($str);
	return $str;
}

/**
 * 错误日志
 * 
 * @param $errno 错误号
 * @param $errstr 错误信息
 * @param $errfile 文件
 * @param $errline 行号
 */
function random_error_handler($errno, $errstr, $errfile, $errline)
{
	if($errno != 8)
	{
		$error_log = isset($GLOBALS['RANDOM']['php_error_log']) ? $GLOBALS['RANDOM']['php_error_log'] : false;
		if ($error_log !== false)
		{
			$errfile = str_replace(APP_ROOT , '', $errfile);
			error_log('<?php exit(); ?>'.date('Y-m-d H:i:s')."\t<".$errstr.">\t\"".$errfile.':'.$errline.'"'.PHP_EOL, 3, $error_log);
		}
	}
	return true;
}

/**
 * 提示信息
 * 
 * @param $text 提示文字
 * @param $url 跳转URL
 * @param $class 类型(error, ok, or)
 * @param $time 等待时间
 */
function showMessage($text, $url = 'back', $class = 'ok', $time = 2)
{
	if ($url == 'back' || $url == '')
	{
		$url = 'history.back(-1);';
	}
	else
	{
		$url = 'location.href=\''.$url.'\'';
		//$url = 'location.replace('.$url.')';
	}
	if ($class == '') $class = 'ok';
	if ($time == '') $time = 2;
	include template('notice', 'common');
	exit;
}

/**
 * 取得客户端IP
 * 
 */
function GetIP()
{
	if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
	{
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}
	elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
	{
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	elseif (isset($_SERVER["REMOTE_ADDR"]))
	{
		$ip = $_SERVER["REMOTE_ADDR"];
	}
	else
	{
		$ip = "Unknown";
	}
	return $ip;
}

/**
 * 获取执行时间
 * 
 */
function debug_time()
{
	return round(microtime(true) - STARTTIME, 6);
}

/**
 * 调试页脚信息
 * 
 */
function debug_footer()
{
	$t = debug_time();
	$q = DB::query_count();
	$m = round(memory_get_usage()/1024/1024, 4);
	return "Processed in {$t} second(s), {$q} Queries, Memory Usage {$m} MB, Gzip enabled";
}
